package cn.boysoft.core.util;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringEscapeUtils;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

/**
 * @author 付厚俊
 * CreateTime 2013-4-5 上午10:29:52
 */
public class JsonUtil {

	public static String toJson(Object target){
		 ObjectMapper objectMapper =  new ObjectMapper();
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		 objectMapper.setDateFormat(format);  
		 StringWriter stringWriter = new StringWriter();
		 try {
			objectMapper.writeValue(stringWriter, target);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return stringWriter.toString();
	}
	public static String formatJson(String targetStr){
		 JsonElement jsonEle = null;
		 String text =targetStr;
		 com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
         Object obj = com.alibaba.fastjson.JSON.parse(text);
         text = com.alibaba.fastjson.JSON.toJSONString(obj,SerializerFeature.WriteMapNullValue);
         jsonEle =  parser.parse(text);
         if(jsonEle!=null && !jsonEle.isJsonNull()){
             GsonBuilder gb = new GsonBuilder();
             gb.setPrettyPrinting();
             gb.serializeNulls();
             Gson gson = gb.create();
             String jsonStr = gson.toJson(jsonEle);
             if(jsonStr!=null){
                 jsonStr = StringEscapeUtils.unescapeJava(jsonStr);
                return jsonStr;
             }
         } 
		return targetStr;
	}
	public static void main(String[] args) throws IOException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException{
		
	}
}
